import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/RegisterView.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/profile',
      redirect: '/'
    },
    {
      path: '/',
      component: () => import('../components/layout/MainLayout.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          name: 'home',
          component: () => import('../views/HomeView.vue'),
          meta: { title: '首页' }
        },
        // 医生工作站
        {
          path: 'doctor',
          meta: { title: '医生工作站', roles: ['doctor'] },
          children: [
            {
              path: 'outpatient',
              meta: { title: '门诊管理' },
              children: [
                {
                  path: 'reception',
                  name: 'doctor-outpatient-reception',
                  component: () => import('../views/outpatient/CallView.vue'),
                  meta: { title: '叫号接诊' }
                },
                {
                  path: 'examination',
                  name: 'doctor-outpatient-examination',
                  component: () => import('../views/outpatient/ExaminationRequestView.vue'),
                  meta: { title: '检查申请' }
                },
                {
                  path: 'laboratory',
                  name: 'doctor-outpatient-laboratory',
                  component: () => import('../views/outpatient/LaboratoryRequestView.vue'),
                  meta: { title: '检验申请' }
                },
                {
                  path: 'records',
                  name: 'doctor-outpatient-records',
                  component: () => import('../views/outpatient/MedicalRecordView.vue'),
                  meta: { title: '门诊病历' }
                }
              ]
            },
            {
              path: 'statistics',
              meta: { title: '统计分析' },
              children: [
                {
                  path: 'workload',
                  name: 'doctor-statistics-workload',
                  component: () => import('../views/statistics/WorkloadView.vue'),
                  meta: { title: '个人工作量统计' }
                },
                {
                  path: 'disease',
                  name: 'doctor-statistics-disease',
                  component: () => import('../views/statistics/DiseaseView.vue'),
                  meta: { title: '疾病统计' }
                }
              ]
            }
          ]
        },
        // 护士工作站
        {
          path: 'nurse',
          meta: { title: '护士工作站', roles: ['nurse'] },
          children: [
            {
              path: 'outpatient',
              meta: { title: '门诊管理' },
              children: [
                {
                  path: 'registration',
                  name: 'nurse-outpatient-registration',
                  component: () => import('../views/outpatient/RegistrationView.vue'),
                  meta: { title: '挂号系统' }
                },
                {
                  path: 'call',
                  name: 'nurse-outpatient-call',
                  component: () => import('../views/outpatient/CallView.vue'),
                  meta: { title: '叫号系统' }
                }
              ]
            },
            {
              path: 'statistics',
              meta: { title: '统计分析' },
              children: [
                {
                  path: 'workload',
                  name: 'nurse-statistics-workload',
                  component: () => import('../views/statistics/WorkloadView.vue'),
                  meta: { title: '护理工作量统计' }
                }
              ]
            }
          ]
        },
        // 系统管理
        {
          path: 'system',
          meta: { title: '系统管理', roles: ['admin'] },
          children: [
            {
              path: 'users',
              name: 'system-users',
              component: () => import('../views/system/UsersView.vue'),
              meta: { title: '用户管理' }
            },
            {
              path: 'permissions',
              name: 'system-permissions',
              component: () => import('../views/system/PermissionsView.vue'),
              meta: { title: '权限管理' }
            },
            {
              path: 'settings',
              name: 'system-settings',
              component: () => import('../views/system/SettingsView.vue'),
              meta: { title: '系统设置' }
            }
          ]
        }
      ]
    }
  ]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  const token = userStore.token // 直接获取 token

  console.log(`Navigating from ${from.path} to ${to.path}`);

  // 1. 处理未登录情况
  if (!token) {
    if (to.meta.requiresAuth) {
      console.log(`Route ${to.path} requires auth, but no token found. Redirecting to login.`);
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      });
    } else {
      console.log(`Route ${to.path} does not require auth. Allowing navigation.`);
      next(); // 允许访问无需认证的页面（如登录、注册）
    }
    return; // 结束处理
  }

  // 2. 处理已登录情况 (有 token)
  // 检查 userInfo 是否已加载
  if (!userStore.userInfo) {
    console.log('Token exists, but userInfo is missing. Fetching user info...');
    try {
        // 如果正在加载，等待加载完成 (简单处理，避免重复请求)
        if (userStore.isLoadingUserInfo) {
            console.log('User info is already loading, waiting...');
            // 可以设置一个简单的轮询或等待机制，或者依赖后续导航触发重新检查
            // 为简化，暂时先阻止本次导航，等待下一次触发
            // next(false); // 阻止导航
            // 或者什么都不做，让其停留在当前页面
             return; // 不调用 next() 会阻止导航
        }

      await userStore.fetchUserInfo();
      // 如果 fetchUserInfo 内部因错误重定向到登录页，这里的代码不会执行
      console.log('User info fetched successfully after checking token.');
      // 获取信息成功后，需要重新检查权限，因为 userInfo 现在应该有了
      // **直接调用 next(to) 可能会导致无限循环，需要显式重新检查或直接放行**
      // 我们在这里简单地允许导航，因为后续的权限检查逻辑会处理
       // next(); // 第一次尝试时直接放行
       // 更好的做法是显式重新检查，但为了避免复杂性，我们依赖下面紧接着的检查
       // 技巧：可以调用 next({ ...to, replace: true }) 强制重新评估路由
       next({ ...to, replace: true });
       return;

    } catch (error) {
      console.error('Error fetching user info during navigation guard:', error);
      // fetchUserInfo 内部应该已经处理了重定向到登录页，这里理论上不需要再次处理
      // 但以防万一，可以再次确保跳转
       if (from.path !== '/login') { // 避免从登录页无限重定向到登录页
            next('/login');
       } else {
           next(false); // 停留在登录页
       }
      return; // 结束处理
    }
  }

  // 3. 用户已登录且 userInfo 已加载
  console.log('User is logged in and userInfo is loaded.', userStore.userInfo);
  // 如果用户已登录并尝试访问登录页或注册页，重定向到首页
  if (to.path === '/login' || to.path === '/register') {
      console.log('Authenticated user trying to access login/register. Redirecting to home.')
      next('/');
      return;
  }

  // 检查角色/组权限
  if (to.meta.roles) {
    const requiredRoles = to.meta.roles as string[];
    const userGroups = userStore.userInfo?.groups || []; // 获取用户组
    const hasRequiredRole = requiredRoles.some(role => userGroups.includes(role)); // 检查是否包含任一所需角色

    console.log(`Checking roles for ${to.path}. Required: ${requiredRoles.join(', ')}. User has: ${userGroups.join(', ')}`);

    if (!hasRequiredRole) {
      console.log(`User does not have required role for ${to.path}. Redirecting to home.`);
      // 如果用户无权访问目标路由，可以重定向到首页或一个无权限页面
      next('/');
      return;
    }
    console.log(`User has required role for ${to.path}. Allowing navigation.`);
  }

  // 4. 所有检查通过，允许导航
  console.log(`All checks passed for ${to.path}. Allowing navigation.`);
  next();
})

export default router 